// pages/statistics/statistics.js
const app = getApp()
import config from '../../utils/config.js';
import util from '../../utils/util.js';
import Toast from '../../vant/toast/toast';
import Dialog from '../../vant/dialog/dialog';
import {
  comModel
} from '../../models/com';
const com = new comModel();
import {
  orderModel
} from '../../models/order';
const order = new orderModel();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    config: config,
    height: app.globalData.height,
    barheight: app.globalData.barheight,
    roleType:app.globalData.roleType,// 角色类别 1食堂人员,2档口人员
    sysBottom: app.globalData.bottom,
    activeIdx: 3,
    stallPriceStatus: '', // 档口角色是否可看商品价格 1显示

    gateNotList:"", // 今日未报单档口

    selectIn: 0, // 0按档口，1按商家

    goodsList:[], // 按档口分的列表
    goodsListShow: [], // 按档口分的列表是否展开
    goodsList2:[], // 按商家分的列表

    allselected: false, // 按档口分的是否全选
    allnum: 0,
    allprices: 0,

    allselected2: false, // 按商家分的是否全选
    allnum2: 0,
    allprices2: 0,

	  fLoad:true,  // 是否第一次打开页面
    showInputDailog: false, // 计步器点击input输入弹窗
    currentValue: '', // 计步器点击input输入弹窗中input中的数值
    isfocus: false, // 计步器点击input输入弹窗中input设置自动聚焦
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 隐藏原生的tabbar
    wx.hideTabBar()
    this.data.fLoad = true
    
    this.getAuth();
  },
  getAuth() {
    var _this = this
    wx.request({
      url: config.projectUrl + 'canteen/canteen/currentCanteenInfo',
      method: 'get',
      header: {
        'authentication': wx.getStorageSync('authentication')
      },
      success: function (res) {
        if(res.data.code == '402'){
          Dialog.confirm({
            title: '提示',
            message: '您还未登录，请先登录再进行操作',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }).catch(() => {
            // on cancel
          });
        }else{
          _this.setData({
            stallPriceStatus: res.data.data.stallPriceStatus
          })
          _this.selectList(true); // 按档口
          // _this.selectList2(); // 按商家
          _this.selectGateNot(); // 今日未报档口
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  if(!this.data.fLoad){
      this.setData({
        goodsList:[],
        goodsList2:[],
        allselected:false,
        allnum:0,
        allprices:0,
        allselected2:false,
        allnum2:0,
        allprices2:0
      })

      this.getAuth();

    }
	  this.data.fLoad = false
    var userInfo = wx.getStorageSync('userInfo')
    this.setData({
      roleType: userInfo.roleType,
      goodsListShow: []
    })

  },

  // 今日未报档口
  selectGateNot(){
    com.apiGateNot({}, res => {
      this.setData({
        gateNotList:res
      })
    })
  },

  // 选择
  select(e){
    if(e.detail.index == 1){ // 按商家
      this.selectList2();
    }else{ // 按档口
      this.selectList(true);
    }
    this.setData({
      selectIn:e.detail.index
    })

  },

  // 按档口查询
  selectList(loadding){
    com.apiWithStall({}, res => {
      var goodsListShow = this.data.goodsListShow
      for(var i=0;i<res.length;i++){
        if(goodsListShow.indexOf(i) != -1){
          res[i].showm = true
        }else{
          res[i].showm = false
        }
      }
      this.setData({
        goodsList:res
      })
      this.updataData(); // 给数据添加是否选中参数
    }, loadding)
  },
   // 按商家查询
  selectList2(){
    com.apiWithSupplier({}, res => {
      this.setData({
        goodsList2:res
      })
      this.updataData2();
    })
  },

  // 给数据添加是否选中参数
  updataData(){
    var goodsList = this.data.goodsList;
    for(var i=0;i<goodsList.length;i++){
      goodsList[i].selected = false;
      var shopList = goodsList[i].shopCarProductListVoList
      for(var j=0;j<shopList.length;j++){
        shopList[j].selected = false;
      }
    }
    this.setData({
      goodsList:goodsList
    })
    // console.log(this.data.goodsList);
  },

  updataData2(){
    var goodsList = this.data.goodsList2;
    for(var i=0;i<goodsList.length;i++){
      goodsList.selected = false;
      goodsList[i].shopCarProductListVoList = goodsList[i].goodList;
      var shopList = goodsList[i].shopCarProductListVoList;
      for(var j=0;j<shopList.length;j++){
        shopList[j].selected = false;
      }
    }
    this.setData({
      goodsList2:goodsList
    })
  },

  // 展开更多
  onMore(e){
    var cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    let index = e.currentTarget.dataset.index //当前店铺下标
    if (cartsdata[index].showm) {
      cartsdata[index].showm = false
      this.getGoodsListShowm(index) // 按档口展开的arr
    } else {
      cartsdata[index].showm = true
      this.getGoodsListShowm(index) // 按档口展开的arr
    }
    if(this.data.selectIn==1){
      this.setData({
        goodsList2: cartsdata //店铺下商品的数量
      })
    }else{
      this.setData({
        goodsList: cartsdata  //店铺下商品的数量
      })
    }
  },
  // 按档口展开的arr
  getGoodsListShowm(index) {
    if(this.data.goodsListShow.indexOf(index) != -1){
      var t = this.data.goodsListShow.indexOf(index)
      this.data.goodsListShow.splice(t, 1)
    }else{
      this.data.goodsListShow.push(index)
    }
  },

  // 商品的选中
  goodsselected: function (e) {
    if(e.currentTarget.dataset.selectable == 0){
      return
    }
    var cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    let index = e.currentTarget.dataset.index //当前商品所在店铺中的下标
    let idx = e.currentTarget.dataset.selectIndex //当前店铺下标
    let cai = cartsdata[idx].shopCarProductListVoList; //当前商品的店铺data.shopCarProductListVoList
    let curt = cai[index]; //当前商品数组
    if (curt.selected) {
      cartsdata[idx].shopCarProductListVoList[index].selected = false //点击后当前店铺下当前商品的状态
      cartsdata[idx].selected = false
    } else {
      cartsdata[idx].shopCarProductListVoList[index].selected = true //点击后当前店铺下当前商品的状态

      //当店铺选中商品数量与店铺总数量相等时 改变店铺状态
      var storegoodsleg = cartsdata[idx].shopCarProductListVoList.length
      var shopCarProductListVoList = cartsdata[idx].shopCarProductListVoList
      var selectedleg = 0
      for (var i in shopCarProductListVoList) {
        if (shopCarProductListVoList[i].selected == true) {
          selectedleg++
        }
      }
      if (storegoodsleg == selectedleg) {
        cartsdata[idx].selected = true
      }
    }

    // 更新
    if(this.data.selectIn==1){
      this.setData({
        goodsList2: cartsdata //店铺下商品的数量
      })
    }else{
      this.setData({
        goodsList: cartsdata  //店铺下商品的数量
      })
    }
    
    this.getallprices(); // 计算总价格
    this.allallprices(); // 全选条件 条件->商铺全选择全选 反之
  },

  // 店铺的选中
  storeselected: function (e) {
    var cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    let index = e.currentTarget.dataset.index //当前店铺下标
    var thisstoredata = cartsdata[index].shopCarProductListVoList //当前店铺商品数据
    //改变当前店铺状态
    if (cartsdata[index].selected) {
      cartsdata[index].selected = false
      //改变当前店铺所有商品状态
      for (var i in thisstoredata) {
        cartsdata[index].shopCarProductListVoList[i].selected = false
      }
    } else {
      cartsdata[index].selected = true
      //改变当前店铺所有商品状态
      for (var i in thisstoredata) {
        if(this.data.selectIn==1){ // 按商家分
          if(cartsdata[index].shopCarProductListVoList[i].shopCarProductListVoList[0].selectableStatus == 1){ // 商家是否营业
            cartsdata[index].shopCarProductListVoList[i].selected = true
          }else{
            cartsdata[index].shopCarProductListVoList[i].selected = false
          }
        }else{ // 按档口家分
          if(cartsdata[index].shopCarProductListVoList[i].selectableStatus == 1){ // 商家是否营业
            cartsdata[index].shopCarProductListVoList[i].selected = true
          }else{
            cartsdata[index].shopCarProductListVoList[i].selected = false
          }
        }
      }
    }
    if(this.data.selectIn==1){
      this.setData({
        goodsList2: cartsdata //店铺下商品的数量
      })
    }else{
      this.setData({
        goodsList: cartsdata  //店铺下商品的数量
      })
    }
    this.getallprices(); // 计算总价格
    this.allallprices(); // 全选条件 条件->商铺全选择全选 反之
  },

  //全选按钮点击
  tapallallprices: function () {
    let allselected = (this.data.selectIn==1?this.data.allselected2:this.data.allselected)
    var cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    if (allselected) {
      allselected = false
    } else {
      allselected = true
    }

    //选择
    for (var i = 0; i < cartsdata.length; i++) {
      cartsdata[i].selected = allselected
      var shopCarProductListVoList = cartsdata[i].shopCarProductListVoList
      for (var a = 0; a < shopCarProductListVoList.length; a++) {
        shopCarProductListVoList[a].selected = allselected
      }
    }
    
    if(this.data.selectIn==1){
      this.setData({
        goodsList2: cartsdata, //店铺下商品的数量
        allselected2:allselected
      })
    }else{
      this.setData({
        goodsList: cartsdata, //店铺下商品的数量
        allselected: allselected
      })
    }
    this.getallprices(); // 计算总价格
  },

  // 全选条件 条件->商铺全选择全选 反之
  allallprices: function () {
    let cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    let storenum = cartsdata.length;
    let allselected = (this.data.selectIn==1?this.data.allselected2:this.data.allselected)
    let allselectednum = 0;
    for (var i = 0; i < cartsdata.length; i++) {
      if (cartsdata[i].selected == true) {
        allselectednum++
      }
    }

    if (storenum == allselectednum) {
      allselected = true
    } else {
      allselected = false
    }
    
    if(this.data.selectIn==1){
      this.setData({
        allselected2: allselected
      })
    }else{
      this.setData({
        allselected: allselected
      })
    }
    this.getallprices(); // 计算总价格
  },

  // 计算总价格  所有选中商品的 （价格*数量）相加
  getallprices: function () {
    let cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    var allprices = 0
    let allnum = 0
    for (var i = 0; i < cartsdata.length; i++) {
      var shopCarProductListVoList = cartsdata[i].shopCarProductListVoList
      for (var a = 0; a < shopCarProductListVoList.length; a++) {
        // 选中且在商家营业范围内
        if (shopCarProductListVoList[a].selected&&shopCarProductListVoList[a].selectableStatus==1) {
          //当前商品价格*数量 +
          if(this.data.selectIn==1){
            allprices += shopCarProductListVoList[a].totalPrice
            allnum += shopCarProductListVoList[a].totalCount   
          }else{
            let price = Number(shopCarProductListVoList[a].price)
            let num = Number(shopCarProductListVoList[a].goodCount) //防止num为字符 *1或parseInt Number
            allprices += price * num
            allnum += num
          }
        }
      }
    }
    //更新已选数量
    if(this.data.selectIn==1){
      this.setData({
        allnum2: allnum,
        allprices2: allprices.toFixed(2)
      })
    }else{
      this.setData({
        allnum: allnum,
        allprices: allprices.toFixed(2)
      })
    }
    
  },
  
  // 点击加号减号增减数量
  onChange: util.throttle(function (e) {
    var goodsCount = e.detail;
    // console.log('onChange',goodsCount)
    var goodsId = e.currentTarget.dataset.id;
    var canteenStallId = e.currentTarget.dataset.sid;
    // var shopCarId = e.currentTarget.dataset.carid;
    let index = e.currentTarget.dataset.index //当前商品所在店铺中的下标
    let idx = e.currentTarget.dataset.selectIndex //当前店铺下标

    // if(!goodsCount || goodsCount==0){ // 数量为0，删除商品
    //   this.onCarDelet(shopCarId,idx,index)
	  //   return
	  // }
    let cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    if(cartsdata.length == 0) { // 触发了按钮，但刷新列表，清除了数据的时候
      return
    }
    let oldCount = cartsdata[idx].shopCarProductListVoList[index].goodCount // 当前商品原数量
    cartsdata[idx].shopCarProductListVoList[index].goodCount = goodsCount // 点击后当前店铺下当前商品的数量
    if(oldCount == goodsCount){
      return
    }
    this.setData({
      goodsList: cartsdata //店铺下商品的数量
    })
    
	  var that = this;
    // 验证计量可否为小数 1 是 0否
    var decimalStatus = cartsdata[idx].shopCarProductListVoList[index].decimalStatus;
    if(decimalStatus != 1){
      if(!util.valZe(goodsCount)){
        util.msg('当前商品数量只能为整数');
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        this.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        return;
      }
    }else{
      if(!util.isMoney(goodsCount)){
        util.msg('当前商品数量格式有误');
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        this.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        return;
      }
    }
    this.getallprices(); // 计算总价格
    com.apiAddshopNoLoad({
      goodsId: goodsId,
      goodsCount: goodsCount,
      canteenStallId: canteenStallId
    }, res => {
      if (res.code == 200) {
        if( goodsCount <= 0){ // 数量为0，删除商品
          cartsdata[idx].shopCarProductListVoList.splice(index,1) // 删除商品
          if( cartsdata[idx].shopCarProductListVoList.length == 0 ) { // 如果档口下没有商品，删除该档口
            cartsdata.splice(idx, 1)
          }
          
          that.setData({
            goodsList: cartsdata
          })
        }
      } else {
        util.msg(res.msg)
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        that.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        // 计算总价格
        that.getallprices();
      }
    })
  },500),

  // 点击input弹窗
  onInput(event)  {
    var goodsId = event.currentTarget.dataset.id;
    var canteenStallId = event.currentTarget.dataset.sid;
    let index = event.currentTarget.dataset.index //当前商品所在店铺中的下标
    let idx = event.currentTarget.dataset.selectIndex //当前店铺下标

    this.submitData = {
      goodsId: goodsId,
      canteenStallId: canteenStallId,
      index: index,
      idx: idx
    }
    this.setData({
      currentValue: event.currentTarget.dataset.currentval,
      showInputDailog: true
    });
    // van-popup中有一个动画效果，所以input的focus效果要做一个延时
    var that = this
    setTimeout(()=>{
      that.setData({
        isfocus: true
      })
    }, 35)
  },
  onFocus(event) {
    if (event.detail.value === '0') {
      this.setData({ currentValue: '' })
    }
  },
  onBlur(event) {
    if (event.detail.value === '') {
      this.setData({ currentValue: '0' })
    }
  },
  // 点击input弹窗-取消
  onCancel() {
    this.setData({showInputDailog: false});
  },
  // 点击input弹窗-确认
  onSure(e) {
    var { goodsCount } = e.detail.value
    // console.log('oninput',goodsCount)
    var goodsId = this.submitData.goodsId;
    var canteenStallId = this.submitData.canteenStallId;
    let index = this.submitData.index //当前商品所在店铺中的下标
    let idx = this.submitData.idx //当前店铺下标

    let cartsdata = (this.data.selectIn==1?this.data.goodsList2:this.data.goodsList) //购物车数据
    let oldCount = cartsdata[idx].shopCarProductListVoList[index].goodCount // 当前商品原数量
    cartsdata[idx].shopCarProductListVoList[index].goodCount = goodsCount // 点击后当前店铺下当前商品的数量
    if(oldCount == goodsCount){
      return
    }
    this.setData({
      goodsList: cartsdata //店铺下商品的数量
    })
    
	  var that = this;
    // 验证计量可否为小数 1 是 0否
    var decimalStatus = cartsdata[idx].shopCarProductListVoList[index].decimalStatus;
    if(decimalStatus != 1){
      if(!util.valZe(goodsCount)){
        util.msg('当前商品数量只能为整数');
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        this.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        return;
      }
    }else{
      if(!util.isMoney(goodsCount)){
        util.msg('当前商品数量格式有误');
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        this.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        return;
      }
    }
    this.getallprices(); // 计算总价格
    com.apiAddshop({
      goodsId: goodsId,
      goodsCount: goodsCount,
      canteenStallId: canteenStallId
    }, res => {
      if (res.code == 200) {
        if( goodsCount <= 0){ // 数量为0，删除商品
          cartsdata[idx].shopCarProductListVoList.splice(index,1) // 删除商品
          if( cartsdata[idx].shopCarProductListVoList.length == 0 ) { // 如果档口下没有商品，删除该档口
            cartsdata.splice(idx, 1)
          }
        }
        that.setData({
          allselected2: false,
          allnum2: 0,
          allprices2: 0,
          goodsList: cartsdata
        })
        that.onCancel() // 关闭弹窗
        
      } else {
        util.msg(res.msg)
        cartsdata[idx].shopCarProductListVoList[index].goodCount = oldCount;
        that.setData({
          goodsList: cartsdata //店铺下商品的数量
        })
        // 计算总价格
        that.getallprices();
      }
    })
  },
  
  // 下单
  onDeclara(){
    var singleOrderList = [];
    if(this.data.selectIn==1){
      var goodsList = this.data.goodsList2 //购物车数据
      for(var i=0;i<goodsList.length;i++){
        goodsList.selected = false;
        var shopList = goodsList[i].shopCarProductListVoList
        for(var j=0;j<shopList.length;j++){
          if(shopList[j].selected){
            var voList = shopList[j].shopCarProductListVoList;
            for(var k=0;k<voList.length;k++){
              var singleOrderAppend = {
                  stallId:voList[k].stallId
              }
              var list = {
                count:voList[k].goodCount,
                goodId:voList[k].goodId,
                singleOrderAppend:JSON.stringify(singleOrderAppend)
              };
              singleOrderList.push(list);
            }
          }
        }
      }
    }else{
      var goodsList = this.data.goodsList //购物车数据
      for(var i=0;i<goodsList.length;i++){
        goodsList.selected = false;
        var shopList = goodsList[i].shopCarProductListVoList
        for(var j=0;j<shopList.length;j++){
          if(shopList[j].selected){
            var singleOrderAppend = {
              stallId:shopList[j].stallId
            }
            var list = {
              count:shopList[j].goodCount,
              goodId:shopList[j].goodId,
              singleOrderAppend:JSON.stringify(singleOrderAppend)
            };
            singleOrderList.push(list);
          }
        }
      }
    }
    
    if(singleOrderList.length==0){
      util.msg('请选择商品');
      return;
    }
    var params = {
      singleOrderList:singleOrderList
    }
    order.apiAddOrder(params, res => {
      // Toast.success('操作成功');
      this.setData({
        goodsList:[],
        goodsList2:[],
        allselected: false,
        allnum: 0,
        allprices: 0,

        allselected2: false,
        allnum2: 0,
        allprices2: 0,
      })
      this.onLoad();
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/order/orderSubmit/orderSubmit?id='+res,
        })
      }, 1000);
    })
  }, 
  
  // 商品详情
  onDetail: util.throttle(function (e) {
    var productId = e.currentTarget.dataset.id
    if (productId) 
      wx.navigateTo({
        url: '/pages/commodity/commodityInfo/commodityInfo?productId=' + productId+'&addt=2',
      })
  }),

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      goodsList:[],
      goodsList2:[],
      goodsListShow: [],
      allselected: false,
      allnum: 0,
      allprices: 0,

      allselected2: false,
      allnum2: 0,
      allprices2: 0,
    })
    if (this.data.selectIn == 1) { // 按商家
      this.selectList2(); // 按商家
      this.selectGateNot(); // 今日未报档口
    } else {
      this.onLoad();
    }
    //模拟加载 		
    setTimeout(function () {		
      wx.hideNavigationBarLoading() //完成停止加载 			
      wx.stopPullDownRefresh() //停止下拉刷新 		
    }, 1500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})